const express = require('express');
const session = require('express-session');
const router = express.Router();
const db = require('./db');
const crypto = require('crypto');
const fs = require('fs')


// 获取商品列表
router.get("/goodslist", (req, res) => {
  // 查询数据库获取商品信息
  const query = `SELECT id, name, price, image,  content, create_time FROM tpadmin_goods_goods `; 
  db.connection.query(query, (error, results) => {
      if (error) {
          console.error('查询失败:', error);
          res.status(500).json({ code: 0, msg: '查询失败' });
      } else {
          // 将查询结果转换为期望的响应格式
          const formattedData = results.map(item => ({
              id: item.id,
              name: item.name,
              price: item.price,
              image: `http://1.12.46.195/img/${item.image}`, // 假设图片存储在http://1.12.46.195/img/
              content: item.content, 
         
              create_time: item.create_time,
          }));

          res.status(200).json({
              code: 1,
              msg: "",
              data: formattedData,
              url: "http://localhost:10086/", // 假设API运行在本地服务器
              wait: 3
          });
      }
  });
});

// 获取单个商品详情
router.get("/goodsinfo", (req, res) => {
  const goodsId = req.query.id; // 获取URL参数中的商品ID
  const query = `SELECT id, name, price,  image, content, create_time FROM tpadmin_goods_goods WHERE id = ? `; 

  db.connection.query(query, [goodsId], (error, results) => {
      if (error) {
          console.error('查询失败:', error);
          res.status(500).json({ code: 0, msg: '查询失败' });
      } else {
          if (results.length === 0) {
              res.status(404).json({ code: 0, msg: '商品不存在' });
          } else {
              // 将查询结果转换为期望的响应格式
              const formattedData = results.map(item => ({
                  id: item.id,
                  goods_category_id: 2, // 假设所有商品的分类ID为2
                  name: item.goods_name,
                  price: item.price,
                  image: `http://1.12.46.195/img/${item.image}`, 
                  content: item.content, 
                  create_time: item.create_time,
              }));

              res.status(200).json({
                  code: 1,
                  msg: "",
                  data: formattedData[0], // 返回第一个结果，即单个商品详情
                  url: "http://localhost:10086/", // 假设API运行在本地服务器
                  wait: 3
              });
          }
      }
  });
});

// 根据多个商品编号获取详情
router.get("/shopcart", (req, res) => {
  const  goodsIds  = req.query.ids; // 从请求体中获取商品ID数组
//   console.log('%cbackend\goodsApi.js:93 goodsIds', 'color: #007acc;', goodsIds);
  if (!Array.isArray(goodsIds) || goodsIds.length === 0) {
      res.status(400).json({ code: 0, msg: '无效的商品ID列表' });
      return;
  }

  // 构建IN语句用于SQL查询
  const idsPlaceholders = goodsIds.map(() => '?').join(', ');
  const query = `SELECT id, name, price, image, content,   create_time  FROM tpadmin_goods_goods WHERE id IN (${idsPlaceholders})`;

  db.connection.query(query, goodsIds, (error, results) => {
      if (error) {
          console.error('查询失败:', error);
          res.status(500).json({ code: 0, msg: '查询失败' });
      } else {
          // 将查询结果转换为期望的响应格式
          const formattedData = results.map(item => ({
              id: item.id,
              name: item.goods_name,
              price: item.price,
              image: `http://1.12.46.195/img/${item.image}`, // 假设图片存储在your_domain.com
              content: item.content, 
              create_time: item.create_time,
          }));

          res.status(200).json({
              code: 1,
              msg: "",
              data: formattedData,
              url: "http://localhost:10086/", // 假设API运行在本地服务器
              wait: 3
          });
      }
  });
});

// 删除商品信息
router.delete('/deletegoods', (req, res) => {
  // 获取要删除的商品id
  const goodsId = req.body.id;
  if (!goodsId) {
    res.status(400).json({ code: 0, msg: '缺少商品id参数' });
    return;
  }

  // 构建删除数据的查询语句
  const query = `
    DELETE FROM tpadmin_goods_goods WHERE id = ?
  `;

  db.connection.query(query, [goodsId], (error, results) => {
    if (error) {
      console.error('删除商品失败:', error);
      res.status(500).json({ code: 0, msg: '删除商品失败' });
    } else {
      // 返回响应结果
      res.json({ code: 1, message: '删除商品成功' });
    }
  });
});

const multer = require('multer');
const path = require('path');

// 配置multer中间件
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, path.join(__dirname, 'img')); // 使用绝对路径
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
  }
});
const upload = multer({ storage });

//添加商品信息
router.post('/addgoods', upload.single('image'), (req, res) => {
  // 获取表单字段的值
  const { name, price,  content } = req.body;

  // 检查必填字段是否存在
  if (!name || !price) {
    res.status(400).json({ code: 0, msg: '缺少必要的商品信息' });
    return;
  }

  // 构建插入数据的查询语句
  const query = `
    INSERT INTO tpadmin_goods_goods (name,  price,  image,  content,  create_time)
    VALUES (?, ?, ?, ?, NOW())
  `;

  db.connection.query(query, [name,  price,  '',  content], (error, results) => {
    if (error) {
      console.error('添加商品失败:', error);
      res.status(500).json({ code: 0, msg: '添加商品失败' });
    } else {
      // 获取上传的图片文件信息
      const image = req.file;

      // 将上传的图片文件移动到static文件夹
      // const newPath = path.join(__dirname, '/static', image.filename);
      const newPath = path.join('/www/dist/img', image.filename);
      fs.rename(image.path, newPath, (moveError) => {
        if (moveError) {
          console.error('移动文件失败:', moveError);
          res.json({ code: 0, message: '添加商品失败' });
        } else {
          // 更新数据库中的图片路径
          const updateQuery = `
            UPDATE tpadmin_goods_goods SET image = ? WHERE id = ?
          `;
          db.connection.query(updateQuery, [image.filename, results.insertId], (updateError, updateResults) => {
            if (updateError) {
              console.error('更新商品图片路径失败:', updateError);
              res.json({ code: 0, message: '添加商品失败' });
            } else {
              // 返回响应结果
              res.json({ code: 1, message: '添加商品成功' });
            }
          });
        }
      });
    }
  });
});



module.exports = router;
